package kotan.view.table;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;

import kotan.model.KindModel;

/**
 * Entity viewer with JTable.
 * 
 * @author shuji.w6e
 * @since 1.0
 */
public class EntityTableView extends JPanel {
    private static final long serialVersionUID = 1L;
    private final JScrollPane scrollPane;
    private DefaultTableColumnModel columnModel;
    final EntityTableModel tableModel = new EntityTableModel();
    EntityTable table;
    final EntityTableControl control;

    /**
     * Constructor.
     */
    public EntityTableView() {
        control = new EntityTableControl(this);
        scrollPane = new JScrollPane();
        columnModel = new DefaultTableColumnModel();
        table = new EntityTable(tableModel, columnModel);
        // Mouse Event
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(final MouseEvent evt) {
                onMouseClicked(evt);
            }
        });
        // Key Event
        table.addKeyListener(new EntityTableKeyListener(this));
        scrollPane.setRowHeaderView(new EntityTableHeader(table));
        scrollPane.setViewportView(table);
        this.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        this.add(scrollPane, gbc);
    }

    protected void onMouseClicked(MouseEvent evt) {
        if (SwingUtilities.isRightMouseButton(evt)) {
            new EntityTableContextMenu().show(evt, this);
        } else {
            if (evt.getClickCount() != 2) return;
            int row = table.columnAtPoint(evt.getPoint());
            int column = table.rowAtPoint(evt.getPoint());
            if (tableModel.isCellSpecialEditable(row, column)) {
                control.editSpecialColumn(row, column);
            }
        }
    }

    public void setKind(KindModel model) {
        int index = 0;
        for (String name : model.propertyNames()) {
            TableColumn column = new TableColumn(index);
            column.setHeaderValue(name);
            column.setPreferredWidth(100);
            columnModel.addColumn(column);
            index++;
        }
        tableModel.setKind(model);
    }

}
